package com.myorg.util.email;

import java.io.File;
import java.io.IOException;
import java.util.Vector;

import com.myorg.util.email.pff.PSTException;
import com.myorg.util.email.pff.PSTFile;
import com.myorg.util.email.pff.PSTFolder;
import com.myorg.util.email.pff.PSTMessage;

public class OutlookStorageTableReader {
	public interface IOutlookEmailProcessor {
		public void process(PSTMessage msg) throws IOException;
	}

	public static void parse(File file, IOutlookEmailProcessor processor) {
		try {
			PSTFile pstFile = new PSTFile(file);
			processFolder(pstFile.getRootFolder(), processor);
		} catch (PSTException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	private static void processFolder(PSTFolder folder,
			IOutlookEmailProcessor processor) throws PSTException,
			java.io.IOException {
		if (folder.hasSubfolders()) {
			Vector<PSTFolder> childFolders = folder.getSubFolders();
			for (PSTFolder childFolder : childFolders) {
				processFolder(childFolder, processor);
			}
		}

		if (folder.getContentCount() > 0) {
			PSTMessage email = (PSTMessage) folder.getNextChild();
			while (email != null) {
				System.out.println("Email: " + email.getSubject());
				email = (PSTMessage) folder.getNextChild();
				processor.process(email);
			}
		}
	}
}
